import './View.css';
import React, { PureComponent as Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Table, Icon, Row, Col, Tooltip, message, Spin, Tabs } from 'antd';
import { Link } from 'react-router-dom';
import AceEditor from 'client/components/AceEditor/AceEditor';
import { formatTime, safeArray } from '../../../../common.js';
import variable from '../../../../constants/variable';
import constants from '../../../../constants/variable.js';
import copy from 'copy-to-clipboard';
import SchemaTable from '../../../../components/SchemaTable/SchemaTable.js';
import { fetchCaseListByInterface } from '../../../../reducer/modules/interfaceCol';

const HTTP_METHOD = constants.HTTP_METHOD;
const { TabPane } = Tabs;

@connect(state => {
  return {
    curData: state.inter.curdata,
    custom_field: state.group.field,
    currProject: state.project.currProject,
    caseListByInterface: (state.interfaceCol && state.interfaceCol.caseListByInterface) || []
  };
}, {
  fetchCaseListByInterface
})
class View extends Component {
  constructor(props) {
    super(props);
    this.state = {
      init: true,
      enter: false,
      loadingCases: false,
      responseJsonCollapsed: false,
      requestJsonCollapsed: false
    };
  }
  static propTypes = {
    curData: PropTypes.object,
    currProject: PropTypes.object,
    custom_field: PropTypes.object,
    caseListByInterface: PropTypes.array,
    fetchCaseListByInterface: PropTypes.func
  };

  // 根据 JSON Schema 生成 JSON 示例
  generateJsonExample(schema) {
    if (!schema) return '{}';
    

    try {
      // 如果 schema 是字符串，先尝试解析
      let parsedSchema = schema;
      if (typeof schema === 'string') {
        try {
          parsedSchema = JSON.parse(schema);
        } catch (parseError) {
          return '{}';
        }
      }
      
      const generateValue = (propSchema) => {
        if (!propSchema) return null;
        
        const type = propSchema.type;
        const format = propSchema.format;
        
        // 优先读取默认值
        if (propSchema.default !== undefined) {
          return propSchema.default;
        }
        
        // 根据类型和格式生成示例值
        switch (type) {
          case 'string':
            if (format === 'email') return 'user@example.com';
            if (format === 'date') return '2024-01-01';
            if (format === 'date-time') return '2024-01-01T00:00:00Z';
            if (format === 'uri') return 'https://example.com';
            if (propSchema.enum && propSchema.enum.length > 0) {
              return propSchema.enum[0];
            }
            if (propSchema.example) return propSchema.example;
            if (propSchema.description) return propSchema.description.substring(0, 20);
            return '示例字符串';
            
          case 'number':
          case 'integer':
            if (propSchema.minimum !== undefined) return propSchema.minimum;
            if (propSchema.maximum !== undefined) return propSchema.maximum;
            if (propSchema.example) return propSchema.example;
            return type === 'integer' ? 0 : 0.0;
            
          case 'boolean':
            return false;
            
          case 'array':
            if (propSchema.items) {
              const itemExample = generateValue(propSchema.items);
              // 如果有默认值，使用默认值；否则生成示例
              return propSchema.default !== undefined ? propSchema.default : [itemExample];
            }
            return propSchema.default !== undefined ? propSchema.default : [];
            
          case 'object':
            if (propSchema.properties) {
              const obj = {};
              for (const key in propSchema.properties) {
                obj[key] = generateValue(propSchema.properties[key]);
              }
              return obj;
            }
            return {};
            
          default:
            return null;
        }
      };
      
      return JSON.stringify(generateValue(parsedSchema), null, 2);
    } catch (error) {
      return '{}';
    }
  }

  // 加载接口用例数据
  loadInterfaceCases = async () => {
    const { curData, fetchCaseListByInterface } = this.props;
    if (!curData || !curData._id) {
      return;
    }
    
    this.setState({ loadingCases: true });
    try {
      await fetchCaseListByInterface(curData._id);
    } catch (error) {
      message.error('加载接口用例失败');
    } finally {
      this.setState({ loadingCases: false });
    }
  };

  req_body_form(req_body_type, req_body_form) {
    if (req_body_type === 'form') {
      const columns = [
        {
          title: '参数名称',
          dataIndex: 'name',
          key: 'name',
          width: 140
        },
        {
          title: '参数类型',
          dataIndex: 'type',
          key: 'type',
          width: 100,
          render: text => {
            text = text || '';
            return text.toLowerCase() === 'text' ? (
              <span>
                <i className="query-icon text">T</i>文本
              </span>
            ) : (
              <span>
                <Icon type="file" className="query-icon" />文件
              </span>
            );
          }
        },
        {
          title: '是否必须',
          dataIndex: 'required',
          key: 'required',
          width: 100
        },
        {
          title: '示例',
          dataIndex: 'example',
          key: 'example',
          width: 80,
          render(_, item) {
            return <p style={{ whiteSpace: 'pre-wrap' }}>{item.example}</p>;
          }
        },
        {
          title: '备注',
          dataIndex: 'value',
          key: 'value',
          render(_, item) {
            return <p style={{ whiteSpace: 'pre-wrap' }}>{item.value}</p>;
          }
        }
      ];

      const dataSource = [];
      if (req_body_form && req_body_form.length) {
        req_body_form.map((item, i) => {
          dataSource.push({
            key: i,
            name: item.name,
            value: item.desc,
            example: item.example,
            required: item.required == 0 ? '否' : '是',
            type: item.type
          });
        });
      }

      return (
        <div style={{ display: dataSource.length ? '' : 'none' }} className="colBody">
          <Table
            bordered
            size="small"
            pagination={false}
            columns={columns}
            dataSource={dataSource}
          />
        </div>
      );
    }
  }
  res_body(res_body_type, res_body, res_body_is_json_schema) {
    if (res_body_type === 'json') {
      if (res_body_is_json_schema) {
        return (
          <div>
            <SchemaTable dataSource={res_body} />
            {/* 返回数据的 JSON 格式显示 */}
            <div style={{ marginTop: '16px' }}>
              <h4 style={{ marginBottom: '8px', color: '#666' }}>返回数据 JSON 格式：</h4>
              <div style={{ 
                backgroundColor: '#f5f5f5', 
                padding: '12px', 
                borderRadius: '4px',
                border: '1px solid #e8e8e8'
              }}>
                <div style={{ marginBottom: '16px' }}>
                  <h5 style={{ marginBottom: '8px', color: '#52c41a', fontSize: '13px' }}>
                    📋 解析后的返回数据示例：
                  </h5>
                  <div style={{ 
                    backgroundColor: '#f6ffed', 
                    padding: '12px', 
                    borderRadius: '4px',
                    border: '1px solid #b7eb8f'
                  }}>
                    <pre style={{ 
                      margin: 0, 
                      fontSize: '12px', 
                      color: '#52c41a',
                      whiteSpace: 'pre-wrap',
                      wordBreak: 'break-all',
                      backgroundColor: 'white',
                      padding: '8px',
                      borderRadius: '4px',
                      border: '1px solid #b7eb8f'
                    }}>
                      {this.generateJsonExample(res_body)}
                    </pre>
                  </div>
                </div>
              </div>
            </div>
          </div>
        );
      } else {
        return (
          <div>
            <div className="colBody">
              <AceEditor data={res_body} readOnly={true} style={{ minHeight: 600 }} />
            </div>
            {/* 返回数据的 JSON 格式显示 */}
            <div style={{ marginTop: '16px' }}>
              <h4 style={{ marginBottom: '8px', color: '#666' }}>返回数据 JSON 格式：</h4>
              {this.renderJsonData(res_body, 'response')}
            </div>
          </div>
        );
      }
    } else if (res_body_type === 'raw') {
      return (
        <div>
          <div className="colBody">
            <AceEditor data={res_body} readOnly={true} mode="text" style={{ minHeight: 300 }} />
          </div>
          {/* 返回数据的原始格式显示 */}
          <div style={{ marginTop: '16px' }}>
            <h4 style={{ marginBottom: '8px', color: '#666' }}>返回数据原始格式：</h4>
            {this.renderJsonData(res_body, 'response')}
            <div style={{ marginTop: '8px', fontSize: '12px', color: '#999' }}>
              注：这是原始返回数据，可能包含特殊字符或格式
            </div>
          </div>
        </div>
      );
    }
  }

  req_body(req_body_type, req_body_other, req_body_is_json_schema) {
    if (req_body_other) {
      let bodyContent;
      if (req_body_is_json_schema && req_body_type === 'json') {
        console.log('SchemaTable 显示数据')
        console.log('SchemaTable req_body_other:', req_body_other)
        bodyContent = <SchemaTable dataSource={req_body_other} />;
        console.log('SchemaTable bodyContent:', bodyContent)
      } else {
        bodyContent = (
          <AceEditor
            data={req_body_other}
            readOnly={true}
            style={{ minHeight: 300 }}
            mode={req_body_type === 'json' ? 'javascript' : 'text'}
          />
        );
      }

      return (
        <div>
          {bodyContent}
          {/* 原始请求参数显示 */}
          <div style={{ marginTop: '16px' }}>
            <h4 style={{ marginBottom: '8px', color: '#666' }}>
              {req_body_is_json_schema ? 'JSON原始数据：' : '原始请求参数：'}
            </h4>
            <div style={{ 
              backgroundColor: '#f5f5f5', 
              padding: '12px', 
              borderRadius: '4px',
              border: '1px solid #e8e8e8'
            }}>
              {req_body_is_json_schema ? (
                // JSON Schema 格式的优化显示
                <div>
                  {/* 解析后的 JSON 示例 */}
                  <div style={{ marginBottom: '16px' }}>
                    <h5 style={{ marginBottom: '8px', color: '#1890ff', fontSize: '13px' }}>
                      📋 解析后的 JSON 示例：
                    </h5>
                    <div style={{ 
                      backgroundColor: '#f0f8ff', 
                      padding: '12px', 
                      borderRadius: '4px',
                      border: '1px solid #d6e4ff'
                    }}>
                      <pre style={{ 
                        margin: 0, 
                        fontSize: '12px', 
                        color: '#1890ff',
                        whiteSpace: 'pre-wrap',
                        wordBreak: 'break-all',
                        backgroundColor: 'white',
                        padding: '8px',
                        borderRadius: '4px',
                        border: '1px solid #d6e4ff'
                      }}>
                        {this.generateJsonExample(req_body_other)}
                      </pre>
                    </div>
                  </div>
                </div>
              ) : (
                // 普通 JSON 格式显示
                this.renderJsonData(req_body_other, 'request')
              )}
            </div>
          </div>
        </div>
      );
    }
  }

  req_query(query) {
    const columns = [
      {
        title: '参数名称',
        dataIndex: 'name',
        width: 140,
        key: 'name'
      },
      {
        title: '是否必须',
        width: 100,
        dataIndex: 'required',
        key: 'required'
      },
      {
        title: '示例',
        dataIndex: 'example',
        key: 'example',
        width: 80,
        render(_, item) {
          return <p style={{ whiteSpace: 'pre-wrap' }}>{item.example}</p>;
        }
      },
      {
        title: '备注',
        dataIndex: 'value',
        key: 'value',
        render(_, item) {
          return <p style={{ whiteSpace: 'pre-wrap' }}>{item.value}</p>;
        }
      }
    ];

    const dataSource = [];
    if (query && query.length) {
      query.map((item, i) => {
        dataSource.push({
          key: i,
          name: item.name,
          value: item.desc,
          example: item.example,
          required: item.required == 0 ? '否' : '是'
        });
      });
    }

    // 检查是否为GET请求，如果是则不显示原始请求参数
    const isGetRequest = this.props.curData && 
                        this.props.curData.method && 
                        this.props.curData.method.toUpperCase() === 'GET';

    return (
      <div>
        <Table bordered size="small" pagination={false} columns={columns} dataSource={dataSource} />
        {/* 原始请求参数 JSON 显示 - GET请求时不显示 */}
        {!isGetRequest && (
          <div style={{ marginTop: '16px' }}>
            <h4 style={{ marginBottom: '8px', color: '#666' }}>原始请求参数：</h4>
            <div style={{ 
              backgroundColor: '#f5f5f5', 
              padding: '12px', 
              borderRadius: '4px',
              border: '1px solid #e8e8e8'
            }}>
              <pre style={{ 
                margin: 0, 
                fontSize: '12px', 
                color: '#333',
                whiteSpace: 'pre-wrap',
                wordBreak: 'break-all',
                backgroundColor: 'white',
                padding: '8px',
                borderRadius: '4px',
                border: '1px solid #e8e8e8'
              }}>
                {JSON.stringify(query || [], null, 2)}
              </pre>
            </div>
          </div>
        )}
      </div>
    );
  }

  countEnter(str) {
    let i = 0;
    let c = 0;
    if (!str || !str.indexOf) {
      return 0;
    }
    while (str.indexOf('\n', i) > -1) {
      i = str.indexOf('\n', i) + 2;
      c++;
    }
    return c;
  }

  componentDidMount() {
    this.loadInterfaceCases();
  }

  componentDidUpdate(prevProps) {
    if (prevProps.curData && this.props.curData &&
        prevProps.curData._id !== this.props.curData._id) {
      this.loadInterfaceCases();
    }
  }

  enterItem = () => {
    this.setState({
      enter: true
    });
  };

  leaveItem = () => {
    this.setState({
      enter: false
    });
  };

  copyUrl = url => {
    copy(url);
    message.success('已经成功复制到剪切板');
  };

  flagMsg = (mock, strice) => {
    if (mock && strice) {
      return <span>( 全局mock & 严格模式 )</span>;
    } else if (!mock && strice) {
      return <span>( 严格模式 )</span>;
    } else if (mock && !strice) {
      return <span>( 全局mock )</span>;
    } else {
      return;
    }
  };

  // 渲染优化的JSON数据
  renderJsonData = (data, type = 'default') => {
    // 尝试解析JSON数据
    let parsedData = null;
    let isJson = false;
    let displayData = data;

    try {
      if (typeof data === 'string') {
        parsedData = JSON.parse(data);
        isJson = true;
        displayData = parsedData;
      } else if (typeof data === 'object' && data !== null) {
        parsedData = data;
        isJson = true;
        displayData = data;
      }
    } catch (e) {
      // 不是有效的JSON，按原样显示
      isJson = false;
    }

    // 如果是JSON数据，使用优化的展示方式
    if (isJson) {
      return (
        <div style={{ 
          backgroundColor: '#f5f5f5', 
          padding: '12px', 
          borderRadius: '4px',
          border: '1px solid #e8e8e8'
        }}>
          {/* JSON数据头部工具栏 */}
          <div style={{
            backgroundColor: '#e8e8e8',
            padding: '8px 12px',
            borderBottom: '1px solid #d9d9d9',
            margin: '-12px -12px 12px -12px',
            borderRadius: '4px 4px 0 0',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center'
          }}>
            <span style={{ 
              fontSize: '12px', 
              fontWeight: '500', 
              color: '#666',
              display: 'flex',
              alignItems: 'center'
            }}>
              <Icon type="code" style={{ marginRight: '6px' }} />
              JSON 数据
            </span>
            <div style={{ display: 'flex', gap: '8px' }}>
              <button
                onClick={() => this.toggleJsonView(type)}
                style={{
                  border: '1px solid #6c757d',
                  backgroundColor: '#fff',
                  borderRadius: '4px',
                  padding: '2px 8px',
                  fontSize: '11px',
                  cursor: 'pointer',
                  color: '#495057'
                }}
              >
                {this.state[`${type}JsonCollapsed`] ? '展开' : '折叠'}
              </button>
              <button
                onClick={() => this.copyJsonData(displayData)}
                style={{
                  border: '1px solid #28a745',
                  backgroundColor: '#fff',
                  borderRadius: '4px',
                  padding: '2px 8px',
                  fontSize: '11px',
                  cursor: 'pointer',
                  color: '#28a745'
                }}
              >
                复制
              </button>
            </div>
          </div>
          
          {/* JSON内容区域 */}
          <div style={{
            maxHeight: this.state[`${type}JsonCollapsed`] ? '200px' : '400px',
            overflow: 'auto',
            transition: 'max-height 0.3s ease'
          }}>
            <pre style={{
              margin: 0,
              fontSize: '12px',
              color: '#333',
              whiteSpace: 'pre-wrap',
              wordBreak: 'break-all',
              backgroundColor: 'white',
              padding: '8px',
              borderRadius: '4px',
              border: '1px solid #e8e8e8'
            }}>
              {this.formatJsonWithSyntaxHighlight(displayData)}
            </pre>
          </div>
        </div>
      );
    }

    // 如果不是JSON，使用普通的pre标签显示，样式与"返回数据 JSON 格式"保持一致
    return (
      <div style={{ 
        backgroundColor: '#f5f5f5', 
        padding: '12px', 
        borderRadius: '4px',
        border: '1px solid #e8e8e8'
      }}>
        <div style={{
          backgroundColor: '#e8e8e8',
          padding: '8px 12px',
          borderBottom: '1px solid #d9d9d9',
          margin: '-12px -12px 12px -12px',
          borderRadius: '4px 4px 0 0'
        }}>
          <span style={{ 
            fontSize: '12px', 
            fontWeight: '500', 
            color: '#666',
            display: 'flex',
            alignItems: 'center'
          }}>
            <Icon type="file-text" style={{ marginRight: '6px' }} />
            文本数据
          </span>
        </div>
        <pre style={{
          margin: 0,
          fontSize: '12px',
          color: '#333',
          whiteSpace: 'pre-wrap',
          wordBreak: 'break-all',
          backgroundColor: 'white',
          padding: '8px',
          borderRadius: '4px',
          border: '1px solid #e8e8e8'
        }}>
          {data}
        </pre>
      </div>
    );
  };

  // 格式化JSON并添加语法高亮
  formatJsonWithSyntaxHighlight = (data) => {
    const jsonString = JSON.stringify(data, null, 2);
    return jsonString;
  };

  // 切换JSON视图的折叠状态
  toggleJsonView = (type) => {
    this.setState(prevState => ({
      [`${type}JsonCollapsed`]: !prevState[`${type}JsonCollapsed`]
    }));
  };

  // 复制JSON数据到剪贴板
  copyJsonData = (data) => {
    try {
      const jsonString = typeof data === 'string' ? data : JSON.stringify(data, null, 2);
      copy(jsonString);
      message.success('JSON数据已复制到剪贴板');
    } catch (error) {
      message.error('复制失败');
    }
  };

  // 渲染结果集区域
  renderResultSet = () => {
    const { caseListByInterface } = this.props;
    const { loadingCases } = this.state;

    if (loadingCases) {
      return (
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <Spin size="large" />
          <div style={{ marginTop: '16px' }}>加载用例数据中...</div>
        </div>
      );
    }

    // 确保 caseListByInterface 是一个数组
    const caseList = Array.isArray(caseListByInterface) ? caseListByInterface : [];

    if (caseList.length === 0) {
      return (
        <div style={{ 
          textAlign: 'center', 
          padding: '40px', 
          color: '#999',
          backgroundColor: '#fafafa',
          borderRadius: '6px'
        }}>
          <Icon type="info-circle" style={{ fontSize: '24px', marginBottom: '8px' }} />
          <div>暂无用例数据</div>
          <div style={{ fontSize: '12px', marginTop: '4px' }}>
            运行接口并保存到集合后，用例数据将显示在这里
          </div>

        </div>
      );
    }

    // 生成页签配置
    const tabPanes = caseList.map((testCase, index) => {
      const tabKey = `case_${index}`;
      const tabTitle = (
        <span>
          <Icon type="play-circle" style={{ color: '#1890ff', marginRight: '4px' }} />
          {testCase.casename || `用例${index + 1}`}
          {testCase.test_status && (
            <span style={{
              marginLeft: '4px',
              padding: '1px 4px',
              borderRadius: '8px',
              fontSize: '10px',
              backgroundColor: testCase.test_status === 'ok' ? '#f6ffed' : '#fff2e8',
              color: testCase.test_status === 'ok' ? '#52c41a' : '#fa8c16'
            }}>
              {testCase.test_status === 'ok' ? '✓' : testCase.test_status === 'error' ? '✗' : '?'}
            </span>
          )}
        </span>
      );

      return (
        <TabPane tab={tabTitle} key={tabKey}>
          <div style={{ padding: '16px' }}>
            {/* 用例基本信息 */}
            <div style={{
              backgroundColor: '#fafafa',
              padding: '12px 16px',
              borderRadius: '6px',
              marginBottom: '16px',
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center'
            }}>
              <div style={{ fontSize: '14px', color: '#666' }}>
                用例ID: {testCase._id || 'N/A'} | 
                创建时间: {testCase.add_time ? formatTime(testCase.add_time) : '未知时间'}
              </div>
            </div>

            {/* 请求和响应数据区域 */}
            <div>
              {/* 请求参数区域 */}
              <div style={{ marginBottom: '24px' }}>
                <h4 style={{ marginBottom: '12px', color: '#333', borderBottom: '2px solid #1890ff', paddingBottom: '4px' }}>
                  📤 请求参数
                </h4>
                <div style={{ marginBottom: '16px' }}>
                  {testCase.req_params && testCase.req_params.length > 0 && (
                    <div style={{ marginBottom: '12px' }}>
                      <h5 style={{ marginBottom: '8px', color: '#666', fontSize: '13px' }}>Path 参数:</h5>
                      <div style={{ backgroundColor: '#f5f5f5', padding: '8px', borderRadius: '4px' }}>
                        {testCase.req_params.map((param, idx) => (
                          <div key={idx} style={{ marginBottom: '4px' }}>
                            <span style={{ fontWeight: 'bold' }}>{param.name}:</span> {param.value}
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {testCase.req_query && testCase.req_query.length > 0 && (
                    <div style={{ marginBottom: '12px' }}>
                      <h5 style={{ marginBottom: '8px', color: '#666', fontSize: '13px' }}>Query 参数:</h5>
                      <div style={{ backgroundColor: '#f5f5f5', padding: '8px', borderRadius: '4px' }}>
                        {testCase.req_query.map((query, idx) => (
                          <div key={idx} style={{ marginBottom: '4px' }}>
                            <span style={{ fontWeight: 'bold' }}>{query.name}:</span> {query.value}
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {testCase.req_headers && testCase.req_headers.length > 0 && (
                    <div style={{ marginBottom: '12px' }}>
                      <h5 style={{ marginBottom: '8px', color: '#666', fontSize: '13px' }}>请求头:</h5>
                      <div style={{ backgroundColor: '#f5f5f5', padding: '8px', borderRadius: '4px' }}>
                        {testCase.req_headers.map((header, idx) => (
                          <div key={idx} style={{ marginBottom: '4px' }}>
                            <span style={{ fontWeight: 'bold' }}>{header.name}:</span> {header.value}
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* 请求体显示 - 根据HTTP方法决定 */}
                  {testCase.req_body_type && testCase.req_body_type !== 'none' && 
                   ((testCase.method && testCase.method.toUpperCase() !== 'GET') || 
                    (this.props.curData && this.props.curData.method && this.props.curData.method.toUpperCase() !== 'GET')) && (
                    <div style={{ marginBottom: '12px' }}>
                      <h5 style={{ marginBottom: '8px', color: '#666', fontSize: '13px' }}>
                        请求体 ({testCase.req_body_type}):
                      </h5>
                      
                      {/* 支持多种form类型 */}
                      {(testCase.req_body_type === 'form' || 
                        testCase.req_body_type === 'form-data' || 
                        testCase.req_body_type === 'application/x-www-form-urlencoded') && 
                        testCase.req_body_form && testCase.req_body_form.length > 0 ? (
                          <div style={{ backgroundColor: '#f5f5f5', padding: '8px', borderRadius: '4px' }}>
                            {testCase.req_body_form.map((form, idx) => (
                              <div key={idx} style={{ marginBottom: '4px' }}>
                                <span style={{ fontWeight: 'bold' }}>{form.name}:</span> {form.value}
                              </div>
                            ))}
                          </div>
                        ) : testCase.req_body_other ? (
                          <div>
                            {this.renderJsonData(testCase.req_body_other, 'request')}
                          </div>
                        ) : (
                          <div style={{ color: '#999', fontStyle: 'italic' }}>
                            无请求体数据
                          </div>
                        )}
                    </div>
                  )}
                  
                  {/* 兜底显示 - GET方法不显示任何请求体 */}
                  {((!testCase.req_body_type || testCase.req_body_type === 'none') && 
                    (testCase.req_body_form && testCase.req_body_form.length > 0 || testCase.req_body_other)) && 
                   ((testCase.method && testCase.method.toUpperCase() !== 'GET') || 
                    (this.props.curData && this.props.curData.method && this.props.curData.method.toUpperCase() !== 'GET')) && (
                    <div style={{ marginBottom: '12px' }}>
                      {/* 表单数据 */}
                      {testCase.req_body_form && testCase.req_body_form.length > 0 && (
                        <div style={{ marginBottom: '12px' }}>
                          <h5 style={{ marginBottom: '8px', color: '#666', fontSize: '13px' }}>
                            请求体数据 (表单数据):
                          </h5>
                          <div style={{ backgroundColor: '#f5f5f5', padding: '8px', borderRadius: '4px' }}>
                            {testCase.req_body_form.map((form, idx) => (
                              <div key={idx} style={{ marginBottom: '4px' }}>
                                <span style={{ fontWeight: 'bold' }}>{form.name}:</span> {form.value}
                              </div>
                            ))}
                          </div>
                        </div>
                      )}
                      
                      {/* 其他请求体数据 */}
                      {testCase.req_body_other && (
                        <div>
                          <h5 style={{ marginBottom: '8px', color: '#666', fontSize: '13px' }}>
                            请求体数据 (无类型):
                          </h5>
                          {this.renderJsonData(testCase.req_body_other, 'request')}
                        </div>
                      )}
                    </div>
                  )}
                  
                  {/* GET方法提示信息 */}
                  {((testCase.method && testCase.method.toUpperCase() === 'GET') || 
                    (this.props.curData && this.props.curData.method && this.props.curData.method.toUpperCase() === 'GET')) && (
                    <div style={{ 
                      marginBottom: '12px', 
                      padding: '8px 12px', 
                      backgroundColor: '#f0f8ff', 
                      border: '1px solid #91d5ff',
                      borderRadius: '4px',
                      fontSize: '12px',
                      color: '#1890ff'
                    }}>
                      <Icon type="info-circle" style={{ marginRight: '4px' }} />
                      GET请求通常没有请求体，参数通过Query和Path传递
                    </div>
                  )}
                </div>
              </div>

              {/* 响应数据区域 */}
              <div>
                <h4 style={{ marginBottom: '12px', color: '#333', borderBottom: '2px solid #52c41a', paddingBottom: '4px' }}>
                  📥 响应数据
                </h4>
                <div>
                  {testCase.test_res_body ? (
                    <div>
                      <h5 style={{ marginBottom: '8px', color: '#666', fontSize: '13px' }}>响应体:</h5>
                      {this.renderJsonData(testCase.test_res_body, 'response')}
                    </div>
                  ) : (
                    <div style={{ color: '#999', fontStyle: 'italic' }}>无响应体数据</div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </TabPane>
      );
    });

    return (
      <Tabs defaultActiveKey="case_0" type="card" size="large">
        {tabPanes}
      </Tabs>
    );
  };

  render() {
    const dataSource = [];
    if (this.props.curData.req_headers && this.props.curData.req_headers.length) {
      this.props.curData.req_headers.map((item, i) => {
        dataSource.push({
          key: i,
          name: item.name,
          required: item.required == 0 ? '否' : '是',
          value: item.value,
          example: item.example,
          desc: item.desc
        });
      });
    }

    const req_dataSource = [];
    if (this.props.curData.req_params && this.props.curData.req_params.length) {
      this.props.curData.req_params.map((item, i) => {
        req_dataSource.push({
          key: i,
          name: item.name,
          desc: item.desc,
          example: item.example
        });
      });
    }
    const req_params_columns = [
      {
        title: '参数名称',
        dataIndex: 'name',
        key: 'name',
        width: 140
      },
      {
        title: '示例',
        dataIndex: 'example',
        key: 'example',
        width: 80,
        render(_, item) {
          return <p style={{ whiteSpace: 'pre-wrap' }}>{item.example}</p>;
        }
      },
      {
        title: '备注',
        dataIndex: 'desc',
        key: 'desc',
        render(_, item) {
          return <p style={{ whiteSpace: 'pre-wrap' }}>{item.desc}</p>;
        }
      }
    ];

    const columns = [
      {
        title: '参数名称',
        dataIndex: 'name',
        key: 'name',
        width: '200px'
      },
      {
        title: '参数值',
        dataIndex: 'value',
        key: 'value',
        width: '300px'
      },
      {
        title: '是否必须',
        dataIndex: 'required',
        key: 'required',
        width: '100px'
      },
      {
        title: '示例',
        dataIndex: 'example',
        key: 'example',
        width: '80px',
        render(_, item) {
          return <p style={{ whiteSpace: 'pre-wrap' }}>{item.example}</p>;
        }
      },
      {
        title: '备注',
        dataIndex: 'desc',
        key: 'desc',
        render(_, item) {
          return <p style={{ whiteSpace: 'pre-wrap' }}>{item.desc}</p>;
        }
      }
    ];
    let status = {
      undone: '未完成',
      done: '已完成'
    };

    let bodyShow =
      this.props.curData.req_body_other ||
      (this.props.curData.req_body_type === 'form' &&
        this.props.curData.req_body_form &&
        this.props.curData.req_body_form.length);

    let requestShow =
      (dataSource && dataSource.length) ||
      (req_dataSource && req_dataSource.length) ||
      (this.props.curData.req_query && this.props.curData.req_query.length) ||
      bodyShow;

    let methodColor =
      variable.METHOD_COLOR[
        this.props.curData.method ? this.props.curData.method.toLowerCase() : 'get'
      ];

    // statusColor = statusColor[this.props.curData.status?this.props.curData.status.toLowerCase():"undone"];
    // const aceEditor = <div style={{ display: this.props.curData.req_body_other && (this.props.curData.req_body_type !== "form") ? "block" : "none" }} className="colBody">
    //   <AceEditor data={this.props.curData.req_body_other} readOnly={true} style={{ minHeight: 300 }} mode={this.props.curData.req_body_type === 'json' ? 'javascript' : 'text'} />
    // </div>
    if (!methodColor) {
      methodColor = 'get';
    }

    const { tag, up_time, title, uid, username } = this.props.curData;

    return (
      <div className="caseContainer">
        <h2 className="interface-title" style={{ marginTop: 0 }}>
          基本信息
        </h2>
        <div className="panel-view">
          <Row className="row">
            <Col span={4} className="colKey">
              接口名称：
            </Col>
            <Col span={8} className="colName">
              <span title={title}>{title}</span>
            </Col>
            <Col span={4} className="colKey">
              创&ensp;建&ensp;人：
            </Col>
            <Col span={8} className="colValue">
              <Link className="user-name" to={'/user/profile/' + uid}>
                <img src={'/api/user/avatar?uid=' + uid} className="user-img" />
                {username}
              </Link>
            </Col>
          </Row>
          <Row className="row">
            <Col span={4} className="colKey">
              状&emsp;&emsp;态：
            </Col>
            <Col span={8} className={'tag-status ' + this.props.curData.status}>
              {status[this.props.curData.status]}
            </Col>
            <Col span={4} className="colKey">
              更新时间：
            </Col>
            <Col span={8}>{formatTime(up_time)}</Col>
          </Row>
          {safeArray(tag) &&
            safeArray(tag).length > 0 && (
              <Row className="row remark">
                <Col span={4} className="colKey">
                  Tag ：
                </Col>
                <Col span={18} className="colValue">
                  {tag.join(' , ')}
                </Col>
              </Row>
            )}
          <Row className="row">
            <Col span={4} className="colKey">
              接口路径：
            </Col>
            <Col
              span={18}
              className="colValue"
              onMouseEnter={this.enterItem}
              onMouseLeave={this.leaveItem}
            >
              <span
                style={{ color: methodColor.color, backgroundColor: methodColor.bac }}
                className="colValue tag-method"
              >
                {this.props.curData.method}
              </span>
              <span className="colValue">
                {this.props.currProject.basepath}
                {this.props.curData.path}
              </span>
              <Tooltip title="复制路径">
                <Icon
                  type="copy"
                  className="interface-url-icon"
                  onClick={() => this.copyUrl(this.props.currProject.basepath + this.props.curData.path)}
                  style={{ display: this.state.enter ? 'inline-block' : 'none' }}
                />
              </Tooltip>
            </Col>
          </Row>
          <Row className="row">
            <Col span={4} className="colKey">
              Mock地址：
            </Col>
            <Col span={18} className="colValue">
              {this.flagMsg(this.props.currProject.is_mock_open, this.props.currProject.strice)}
              <span
                className="href"
                onClick={() =>
                  window.open(
                    location.protocol +
                      '//' +
                      location.hostname +
                      (location.port !== '' ? ':' + location.port : '') +
                      `/mock/${this.props.currProject._id}${this.props.currProject.basepath}${
                        this.props.curData.path
                      }`,
                    '_blank'
                  )
                }
              >
                {location.protocol +
                  '//' +
                  location.hostname +
                  (location.port !== '' ? ':' + location.port : '') +
                  `/mock/${this.props.currProject._id}${this.props.currProject.basepath}${
                    this.props.curData.path
                  }`}
              </span>
            </Col>
          </Row>
          {this.props.curData.custom_field_value &&
            this.props.custom_field.enable && (
              <Row className="row remark">
                <Col span={4} className="colKey">
                  {this.props.custom_field.name}：
                </Col>
                <Col span={18} className="colValue">
                  {this.props.curData.custom_field_value}
                </Col>
              </Row>
            )}
        </div>
        {this.props.curData.desc && <h2 className="interface-title">备注</h2>}
        {this.props.curData.desc && (
          <div
            className="tui-editor-contents"
            style={{ margin: '0px', padding: '0px 20px', float: 'none' }}
            dangerouslySetInnerHTML={{ __html: this.props.curData.desc }}
          />
        )}
        <h2 className="interface-title" style={{ display: requestShow ? '' : 'none' }}>
          请求参数
        </h2>
        {req_dataSource.length ? (
          <div className="colHeader">
            <h3 className="col-title">路径参数：</h3>
            <Table
              bordered
              size="small"
              pagination={false}
              columns={req_params_columns}
              dataSource={req_dataSource}
            />
          </div>
        ) : (
          ''
        )}
        {dataSource.length ? (
          <div className="colHeader">
            <h3 className="col-title">Headers：</h3>
            <Table
              bordered
              size="small"
              pagination={false}
              columns={columns}
              dataSource={dataSource}
            />
          </div>
        ) : (
          ''
        )}
        {this.props.curData.req_query && this.props.curData.req_query.length ? (
          <div className="colQuery">
            <h3 className="col-title">Query：</h3>
            {this.req_query(this.props.curData.req_query)}
          </div>
        ) : (
          ''
        )}

        <div
          style={{
            display:
              this.props.curData.method &&
              HTTP_METHOD[this.props.curData.method.toUpperCase()].request_body
                ? ''
                : 'none'
          }}
        >
          <h3 style={{ display: bodyShow ? '' : 'none' }} className="col-title">
            Body: {this.props.curData.method && this.props.curData.method.toUpperCase() === 'POST' ? (
              <span style={{ 
                fontSize: '14px', 
                fontWeight: 'normal', 
                color: '#1890ff',
                marginLeft: '8px'
              }}>
                ({this.props.curData.req_body_type === 'form' ? 'form-data' : 'JSON'})
              </span>
            ) : ''}
          </h3>
          {this.props.curData.req_body_type === 'form'
            ? this.req_body_form(this.props.curData.req_body_type, this.props.curData.req_body_form)
            : this.req_body(
                this.props.curData.req_body_type,
                this.props.curData.req_body_other,
                this.props.curData.req_body_is_json_schema
              )}
        </div>

             
        <h2 className="interface-title">返回数据</h2>
        {this.res_body(
          this.props.curData.res_body_type,
          this.props.curData.res_body,
          this.props.curData.res_body_is_json_schema
        )}

        {/* 结果集区域 */}
        <div style={{ marginTop: '32px' }}>
          <h2 className="interface-title">
            📊 结果集
          </h2>
          <div style={{ marginTop: '16px' }}>
            {this.renderResultSet()}
          </div>
        </div>
      </div>
    );
  }
}

export default View;
